<template>
  <a-modal
      v-model:visible="visible"
      :title="modalTitle"
      width="45%"
      @ok="handleOk"
      @cancel="handleCancel"
  >
    <a-form ref="formRef">
      <a-form-item>
        <a-button type="primary" @click="handleAdd">新增</a-button>
      </a-form-item>
      <a-form-item
          v-for="(item,index) in cardList"
          label="虚拟卡密 卡号"
          name="card_code"
      >
        <a-row>
          <a-col :span="10">
            <a-input v-model:value="item.code" placeholder="请输入卡号" style="width: 300px" allow-clear/>
          </a-col>
          <a-col :span="10">
            <a-input v-model:value="item.pwd" placeholder="请输入卡密" style="width: 300px" allow-clear/>
          </a-col>
          <a-col :span="4">
            <a-button danger type="primary" @click="handleDel(index)" v-if="cardList.length!==1">删除</a-button>
          </a-col>
        </a-row>

      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import useModal from "@/utils/useModal";
import {reactive, ref} from "vue";
import {addVirtuallyCard} from "@/api/goods/goods";
import {message} from "ant-design-vue";

const {visible, modalTitle} = useModal();
const formRef = ref();
const emits = defineEmits(["model-success"]);

const formState = reactive({
  card_code: null, //虚拟用户个数
});
const cardList = reactive([{
  code: '',
  pwd: '',
}])

const show = (model) => {
  visible.value = true;
  modalTitle.value = "添加虚拟卡号";
  formState.id = model.goods_id;
};
const handleOk = async () => {
  if (cardList.length && cardList.every(o => o.code && o.pwd)) {
    // 格式 卡号:卡密; 多个;隔开

    let ls = cardList.map(item => {
      return item.code + ':' + item.pwd
    })
    formState.card_code = ls.join(';')
    addVirtuallyCard({
      id: formState.id,
      ...formState,
    }).then((res) => {
      if (res.code === 0) {
        message.success(res.msg);
        cardList.length = 0
        cardList.push({
          code: '',
          pwd: '',
        })
        visible.value = false;
        emits("model-success");
      }
    });
  } else {
    message.error('请输入卡号卡密')
  }

};
const handleAdd = () => {
  cardList.push({
    code: '',
    pwd: '',
  })
}
const handleDel = (index) => {
  cardList.splice(index, 1)
}
const handleCancel = () => {
  formRef.value.resetFields();
};
defineExpose({
  show,
});
</script>